<template>
  <Dialog width="1200px" v-model="dialogVisible" :close-on-click-modal="false" :title="(editObj ? '编辑' : '新增') + '虚拟商品SKU'">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="150px"
    >
      <el-form-item label="状态：" prop="status">
        <el-radio-group
          v-model="formData.status"
          class="w-80"
        >
          <el-radio :label="EnumSkuStatus.ENABLE" class="radio">上架</el-radio>
          <el-radio :label="EnumSkuStatus.DISABLE" >下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="排序：" prop="sort">
        <el-input-number v-model="formData.sort" :min="1" />
      </el-form-item>
      <el-form-item label="SKU名称：" prop="name">
        <el-input  v-model="formData.name" placeholder="请输入"/>
      </el-form-item>
      <el-form-item label="SKU描述：" prop="introduction">
        <el-input  v-model="formData.introduction" placeholder="请输入"/>
      </el-form-item>
      <el-form-item :label="'原价' + (currencyData ? '(' + currencyData.currencyName + ')' : '') + '：'" prop="marketPrice">
        <el-input-number v-model="formData.marketPrice" :min="0.01" :precision="2" :step="0.01" />
      </el-form-item>
      <el-form-item :label="'售价' +  (currencyData ? '(' + currencyData.currencyName + ')' : '')+ '：'" prop="price">
        <el-input-number v-model="formData.price" :min="0.01" :precision="2" :step="0.01" />
      </el-form-item>
      <el-form-item label="关联：" prop="esProductId">
        <el-button @click="showEsimChooser" size="small">选择关联</el-button>
      </el-form-item>
    </el-form>
    <VirtualProductSkuChoosedEsimInfo :data="esimProduct" v-if="esimProduct && formData.esProductId" />
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <ESIMChooser @choose="chooseESIMHandler" ref="esimChooserRef" />
</template>
<script lang="ts" setup>
import {propTypes} from "@/utils/propTypes";
import {createSku, updateSku} from '@/api/mall/product/spu';
import {getEsProduct} from '@/api/esim/esproduct/index';
import ESIMChooser from '@/views/esim/esproduct/components/Chooser.vue';
import {EnumDeliveryMethodType, EnumSkuStatus} from "@/config/spu";
import * as ProductSpuApi from "@/api/mall/product/spu";
import {useUpload} from "@/components/UploadFile/src/useUpload";
import VirtualProductSkuChoosedEsimInfo from './../components/VirtualProductSkuChoosedEsimInfo.vue'
import {ExchangeRateApi} from "@/api/mall/currency/rate";

defineOptions({ name: 'ProductVirtualProductSkuUpdateForm' })
const props = defineProps({
  spuId: propTypes.number.def(undefined),
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
})
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const editObj = ref(null);
const esimChooserRef = ref();
let esimProduct = ref(null);
const currencyData = ref(null)
const spuData = ref({});
const formData = ref({
  spuId: undefined,
  id: undefined,
  status: EnumSkuStatus.DISABLE,
  sort: 0,
  name: '',
  introduction: '',
  marketPrice: 0,
  price: 0,
  esProductId: undefined,
})
const formRules = reactive({
  status: [{ required: true, message: '', trigger: 'blur' }],
  sort: [{ required: true, message: '', trigger: 'blur' }],
  name: [{ required: true, message: '', trigger: 'blur' }],
  marketPrice: [{ required: true, message: '', trigger: 'blur' }],
  price: [{ required: true, message: '', trigger: 'blur' }],
  esProductId: [{ required: true, message: '请设置关联', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const emit = defineEmits(['updateSuccess', "createSuccess"])

const getEsimInfo = async ()=> {
  if(!formData.value.esProductId) {
    return;
  }

  return new Promise(resolve => {
    getEsProduct(formData.value.esProductId).then((data)=> {
      esimProduct.value = data;
    }).finally(()=> {
      resolve(true);
    });
  })
}

const getSpuDetail = async ()=> {
  if(props.spuId) {
    const res = (await ProductSpuApi.getSpu(props.spuId)) as ProductSpuApi.Spu

    spuData.value = res;
    getCurrencyRateData();
  }
}

/** 打开弹窗 */
const open = async (obj?: any) => {
  dialogVisible.value = true
  editObj.value = obj;

  getSpuDetail();
  formData.value = {
    spuId: undefined,
    id: undefined,
    status: EnumSkuStatus.DISABLE,
    sort: 0,
    name: '',
    introduction: '',
    price: 0,
    marketPrice: 0,
    esProductId: undefined,
  }
  // 获取数据
  if (obj) {
    Object.assign(formData.value, obj);
    if(formData.value.price) {
      formData.value.price /= 100;
    }
    if(formData.value.marketPrice) {
      formData.value.marketPrice /= 100;
    }

    await getEsimInfo();
  }
}

const close = async ()=> {
  dialogVisible.value = false;
}

const chooseESIMHandler = async (item)=> {
  formData.value.esProductId = item.id;
  esimChooserRef.value.close();
  await getEsimInfo();
}

const showEsimChooser = ()=> {
  esimChooserRef.value.open();
}

const getCurrencyRateData = ()=> {
  if(!spuData.value.currencyCode) {
    return;
  }

  ExchangeRateApi.getExchangeRatePage({
    pageNo: 1,
    pageSize: 1,
    currencyCode: spuData.value.currencyCode
  }).then(({list})=> {
    if(list.length) {
      currencyData.value = list[0];
    }
  });
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return

  let data = {
    ...formData.value
  };
  try {
    formLoading.value = true;
    data.spuId = +props.spuId as number;
    data.price = formData.value.price * 100;
    data.marketPrice = formData.value.marketPrice * 100;

    if(data.id) {
      await updateSku(data)
      emit("updateSuccess");
      message.success("更新成功")
    } else {
      await createSku(data);
      emit("createSuccess");
      message.success("创建成功")
    }
    formLoading.value = false
  } catch (e) {
    formLoading.value = false
  }
}
</script>
